<template>
  <div>
    <el-form ref="form" :model="parameterJson" label-width="120px">
      <el-row>
        <el-col :span="6" v-for="(item,index) in templateList" :key="index">
          <el-form-item :label="item.name">
            <el-input v-model="item.value"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="text-align: center">
        <el-button type="primary" @click="save">保存</el-button>
      </el-row>
    </el-form>
  </div>
</template>
<script>
  export default {
    components: {
    },
    props:{
      categoryId: null,
      productId: null
    },
    watch:{
      categoryId:function (newVal,oldVal) {
        this.loadData(newVal)
      }
    },
    data() {
      return {
        parameterJson:{},
        templateList:[]
      }
    },
    mounted: function () {
      this.loadData(this.categoryId)
    },
    methods: {
      loadData(id){
        let that = this;
        this.utils.request.getProductParameterJson({
          categoryId:id,
          productId:that.productId
        }, function (res) {
          let data = res.data;
          if(data){
            that.templateList = data.templateList
            if(data.parameterJson){
              that.parameterJson = JSON.parse(data.parameterJson)
              for (let i = 0; i < that.templateList.length; i++) {
                let item = that.templateList[i];
                let name = item.name;
                for(let key in that.parameterJson){
                  if(name == key){
                    const value = that.parameterJson[key]
                    that.$set(item,'value',value)
                  }
                }
              }
            } else {
              that.parameterJson = {}
            }
          }
        });
      },
      save(){
        this.templateList.forEach(item=>{
          let name = item.name;
          let value = item.value;
          this.$set(this.parameterJson,name,value||'')
        })
        let that = this;
        this.utils.request.updateProductParameterJson({
          parameterJson: JSON.stringify(that.parameterJson),
          id:that.productId
        }, function (res) {
          if(res.code=='0000'){
            that.$message.success("保存成功")
            that.loadData(that.categoryId)
          } else {
            that.$message.error("保存失败")
          }
        });
      }
    }
  }
</script>
<style scoped lang="scss">

</style>
